﻿@{
    ViewBag.Title = "库存台账";
    Layout = "~/Views/Shared/_ManufactureList.cshtml";
}
<link href="~/Content/css/statistic_ledger.css" rel="stylesheet" />
<link href="~/Content/css/ContainerLedger_print.css" rel="stylesheet" media="print" />
<script type="text/javascript">
    $(function () {
        Index.init();
    });

    var Index = {
        defaultDate:@Html.Raw(ViewData["LedgerDate"].ToString()),
        curUnit:'@ViewData["curUnit"].ToString()',
        curUserName:'@ViewData["curUserName"].ToString()',
        curDate:'@ViewData["curDate"].ToString()',
        curTime:'@ViewData["curTime"].ToString()', 
        printItemTemplate:"",
        dataList:null,
        init: function () {
            with (Index) {
                printItemTemplate = $("#print .page").html();

                initControl();

                initDicData();

                with(Index){
                    loadData(function(data){
                        var columnInfo = [
                                { caption: '容器编号', name: 'FContainerNO'},
                                { caption: '容器名称', name: 'FContainerName'},
                                { caption: "即时库存", name: "FImmeQuantity" },
                                { caption: '账面库存', name: 'FBookQuantity'},
                                { caption: '单价(元)', name: 'FPrice'},
                                { caption: '账面金额（元）', name: 'FBookMoney'},
                                { caption: '容器分类', name: 'FContainerTypeName'}
                        ];

                        dataList = data.rows;
                        
                        renderPrintData($("#print"),data.rows,columnInfo);
                    });
                }
            }
        },
        initControl: function () {
            $("#FAccountDate1").val(Index.defaultDate);

            var tmp = new Date().format("yyyyMM"),date="";

            date={year:tmp.substr(0,4),month:tmp.substr(4,2)};

            $("h1").text("{year}年{month}月零部件库存目录".format(date));

            $("[date-control]").on("click", function () {
                WdatePicker({ dateFmt: 'yyyyMM', minDate: '2000-1', maxDate: '2050-12' });
            });

            $("#gridList").delegate("a[明细账页]","click",function(){
                var num = $.trim($(this).parents("tr").attr("id"));

                var r = Index.dataList[num-1];

                var jsonData = {param:JSON.stringify(r),FAccountDate:Index.defaultDate};
                
                var url = "/WareHouse/Container/ContainerLedgerDetails?{0}".format($.param(jsonData));

                location.href = url;
            });
            
            $("#gridList").delegate("a[统计台账]","click",function(){
                var num = $.trim($(this).parents("tr").find("td:first").text());

                var r = Index.dataList[num-1];

                var jsonData = {param:JSON.stringify(r),FAccountDate:Index.defaultDate};
                
                var url = "/WareHouse/Container/ContainerLedgerStatistics?{0}".format($.param(jsonData));

                location.href = url;
            });

            $("#butnQuery").on("click", function () {
                var $gridList = $("#gridList");

                var conn1 = $.buildPostParam("FAccountDate,FContainerNO,FContainerTypeNO", "1");

                conn1["isDefaultDate"] = Index.defaultDate == $("#FAccountDate1").val();

                $gridList.jqGrid('setGridParam', {
                    postData: conn1,
                }).trigger('reloadGrid');
            });

            $("#butnPrint").on("click",function(){
                var tmp = $("#FAccountDate1").val(),date="";

                date={year:tmp.substr(0,4),month:tmp.substr(4,2)};

                $("h1").text("{year}年{month}月零部件库存目录".format(date));

                $("#print").jqprint();
            });

            //导出
            $("#butnExport").on("click", function () {
                var param = { id: "V_RQK_21_KC_StoConStockCata", param: Index.buildExportConn("FAccountDate,FContainerNO,FContainerTypeNO".split(","), "1") };

                (Index.defaultDate != $("#FAccountDate1").val()) && (param["id"] = "V_RQK_22_KC_StoConStockCata_Arc");

                var url = "/Common/ExcelExportById?{0}".format($.param(param));

                location.href = url;
            });
        },initDicData:function(){
            $("#FContainerTypeNO1").bindSelect({
                url: "/WareHouse/Container/GetContainerTypeNO",
                id: "FTypeNO",
                text: "FTypeNOName"
            });
        },
        loadData:function(onLoadComplate){
            var conn1 = $.buildPostParam("FAccountDate,FContainerNO,FContainerTypeNO", "1");

            conn1["isDefaultDate"] = Index.defaultDate == $("#FAccountDate1").val();

            var $gridList = $("#gridList");
            
            var buildOperate = function(cellvalue, options, rowObject){
                var template = "<a href=\"javascript:void(0);\" 明细账页>明细账页</a><a href=\"javascript:void(0);\" 统计台账>统计台账</a>";

                return template;
            }
         
            $gridList.dataGridForJson({
                url: "/WareHouse/Container/GetContainerLedgers",
                height: $(window).height() - 140,
                colModel: [
                { label: '操作', name: 'FContainerNO', width: 180, align: 'center',formatter:buildOperate, frozen: true },
                { label: '容器编号', name: 'FContainerNO', width: 100, align: 'left', frozen: true },
                { label: '容器名称', name: 'FContainerName', width: 160, align: 'left', frozen: true },
                { label: "即时库存", name: "FImmeQuantity", width: 80, align: 'right'},
                { label: '账面库存', name: 'FBookQuantity', width: 80, align: 'right'},
                { label: '单价(元)', name: 'FPrice', width: 80, align: 'right'},
                { label: '账面金额（元）', name: 'FBookMoney', width: 80, align: 'right'},
                { label: '容器分类(隐藏)', name: 'FContainerTypeNO',  width: 80, align: 'right',hidden:true},
                { label: '容器分类', name: 'FContainerTypeName', width: 160, align: 'center'},
                { label: '最高存储(隐藏)', name: 'FHighestStore', formatter: 'number', width: 100, align: 'right',hidden:true},
                { label: '最低存储(隐藏)', name: 'FLowestStore', formatter: 'number', width: 100, align: 'right',hidden:true},
                { label: '', name: '', width: $(window).width() - 980, align: 'left' }
                ],
                postData:conn1,
                pager: "#gridPager",
                sortname: 'UseUnit,FContainerNO',
                sortorder:"asc",
                viewrecords: true,
                rownumWidth: 50,
                loadComplete: function (data) {  
                    onLoadComplate&&onLoadComplate(data);
                }  
            });
            
        },
        renderPrintData:function(c,data,colunmInfo){
            c.empty();
            
            var rows = 16;

            var max = data.length;
            
            var item = {page:1,maxPage:1,title:$("#wrapper h1").text() ,unit:Index.curUnit,user:Index.curUserName,date:Index.curDate,time:Index.curTime,table:null};

            var maxPage = Math.ceil(max/rows);

            item.maxPage = maxPage;

            for(var i = 0;i < maxPage;i++){
                var isFirst = true;

                var start = i*rows,end=(i+1)*rows;

                end>max && (end=max);

                var table = $("<table>"),pageItem = $("<div>").addClass("page");

                item.page = i+1;
                
                for(var j = start;j<end; j++){
                    var cur = data[j];

                    isFirst && (function(){
                        var title = $("<tr>");

                        for(var idx in colunmInfo){
                            $("<th>").text(colunmInfo[idx].caption).appendTo(title);
                        }

                        title.appendTo(table);

                        isFirst = false;
                    })();

                    !isFirst && (function(){
                        var row = $("<tr>");

                        for(var idx in colunmInfo){
                            $("<td>").text(cur[colunmInfo[idx].name]).appendTo(row);
                        }

                        row.appendTo(table);
                    })();
                }
                
                item.table = "<table>{0}</table>".format(table.html());

                pageItem.html(Index.printItemTemplate.format(item)).appendTo(c);
            }
        },
        buildExportConn: function (params, num) {
            var conn = "";

            !num && (num = "");

            params.forEach(function (item) {
                var val = $("#{0}{1}".format(item, num)).val();

                !!val && (conn += ("and {0} = '{1}'".format(item, val)));
            });

            return conn;
        }
    };

</script>
<div id="wrapper">
    <h1>库存台账</h1>
    <header>
        <div class="f_l">
            <div class="input_area">
                <h2 class="input_title">台账日期</h2>
                <div class="input_c  input_c_w12" style="width: 8.5em;">
                    <input id="FAccountDate1" name="date" type="text" class="txt_common" date-control />
                </div>
            </div>
            <div class="input_area">
                <h2 class="input_title">容器编号</h2>
                <div class="input_c input_c_w12">
                    <input id="FContainerNO1" name="no" type="text" class="txt_common" />
                </div>
            </div>
            <div class="input_area input_c_w12">
                <h2 class="input_title">容器分类</h2>
                <div class="input_c">
                    <select id="FContainerTypeNO1" name="sp" class="sel_common">
                        <option value="">请选择</option>
                    </select>
                </div>
            </div>
        </div>
        <div class="f_r">
            <button id="butnQuery" class="butn_common">
                <span class="glyphicon glyphicon-find"></span>查询
            </button>
            <button id="butnRefresh" class="butn_common" onclick="$.reload()">
                <span class="glyphicon glyphicon-refresh"></span>刷新
            </button>
            <button id="butnPrint" class="butn_common">
                <span class="glyphicon glyphicon-print"></span>打印
            </button>
            <button id="butnExport" class="butn_common">
                <span class="glyphicon glyphicon-export"></span>导出
            </button>
        </div>
    </header>
    <div class="table_c">
        <table id="gridList"></table>
        <div id="gridPager"></div>
    </div>
</div>
<div id="print">
    <div class="page break_page">
        <h1>{title}</h1>
        <div class="top">
            <div class="right_page">第{page}页，共{maxPage}页</div>
        </div>
        <div class="table_c">
            {table}
        </div>
        <footer>
            <span>打印人员：<label>{user}</label></span> <span>打印日期：<label>{date}</label><label>{time}</label></span>
        </footer>
    </div>
</div>

